package com.inossem.warehousestorage_inossem.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Point;
import android.text.method.ScrollingMovementMethod;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.inossem.utils.base.PackageUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.dialog.BaseDialog;
import com.inossem.utils.download.DownloadUtils;
import com.inossem.utils.encryption.MD5Utils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.application.WarehouseStorageApplication;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.zhy.android.percent.support.PercentRelativeLayout;

import java.io.File;

/**
 * Created by leij on 2017/9/2.
 */

public class UpgradeVersionDialogUtils {

    private static DownloadRequest mDownloadRequest;

    public static abstract class UpgradeVersionListener {
        public abstract void upgrade();

        public abstract void upgradeAgain();

        public abstract void exit();
    }

    private static class ViewHolder {
        private TextView prompt, description, versionName, errorMessage, upgrade, upgradeAgain, exit;

        private PercentRelativeLayout upgradeLayout, upgradingLayout, upgradeErrorLayout;

        private NumberProgressBar numberProgressBar;
    }

    public static Dialog getUpgradeVersionDialog(final Context context, String size, String versionName, String description, String url, String md5, UpgradeVersionListener upgradeVersionListener) {
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point point = new Point();
        display.getSize(point);
        BaseDialog baseDialog = BaseDialog.createDialog(context, R.layout.dialog_upgrade_version, null, WindowManager.LayoutParams.WRAP_CONTENT, (Context con, View view, Dialog dialog) -> {
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.prompt = (TextView) view.findViewById(R.id.prompt);
            viewHolder.description = (TextView) view.findViewById(R.id.description);
            viewHolder.description.setMovementMethod(ScrollingMovementMethod.getInstance());
            viewHolder.versionName = (TextView) view.findViewById(R.id.versionName);
            viewHolder.errorMessage = (TextView) view.findViewById(R.id.errorMessage);
            viewHolder.upgrade = (TextView) view.findViewById(R.id.upgrade);
            viewHolder.upgradeAgain = (TextView) view.findViewById(R.id.upgradeAgain);
            viewHolder.exit = (TextView) view.findViewById(R.id.exit);
            viewHolder.upgradeLayout = (PercentRelativeLayout) view.findViewById(R.id.upgradeLayout);
            viewHolder.upgradingLayout = (PercentRelativeLayout) view.findViewById(R.id.upgradingLayout);
            viewHolder.upgradeErrorLayout = (PercentRelativeLayout) view.findViewById(R.id.upgradeErrorLayout);
            viewHolder.numberProgressBar = (NumberProgressBar) view.findViewById(R.id.numberProgressBar);
            viewHolder.prompt.setText("更新提示");
            viewHolder.description.setText(description);
            viewHolder.versionName.setText(versionName + " ( " + Utils.getPrintSize(Long.parseLong(size)) + " )");
            viewHolder.upgradeLayout.setVisibility(View.VISIBLE);
            viewHolder.upgradingLayout.setVisibility(View.GONE);
            String fileName = DownloadUtils.APK_FILE_NAME + versionName + DownloadUtils.APK_SUFFIX_NAME;
            if (DownloadUtils.isApkExist(context, fileName) && md5.equals(MD5Utils.encryptFile(new File(DownloadUtils.getDownloadApkPath(context), fileName)))) {
                LogUtils.i("文件存在，MD5值匹配");
                viewHolder.upgrade.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View v) {
                        WarehouseStorageApplication.getInstance().removeAllActivity();
                        PackageUtils.installNormal(context, DownloadUtils.getDownloadApkPath(context) + File.separator + fileName);
                    }
                });

            } else {
                viewHolder.upgrade.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View v) {
                        LogUtils.i("升级");
                        viewHolder.upgradeLayout.setVisibility(View.GONE);
                        viewHolder.upgradingLayout.setVisibility(View.VISIBLE);
                        viewHolder.upgradeErrorLayout.setVisibility(View.GONE);
                        download(context, url, fileName, md5, viewHolder);
                        if (upgradeVersionListener != null) {
                            upgradeVersionListener.upgrade();
                        }
                    }
                });
            }


            viewHolder.upgradeAgain.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    LogUtils.i("重新下载");
                    download(context, url, DownloadUtils.APK_FILE_NAME + versionName + DownloadUtils.APK_SUFFIX_NAME, md5, viewHolder);
                    if (upgradeVersionListener != null) {
                        upgradeVersionListener.upgradeAgain();
                    }
                }
            });

            viewHolder.exit.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    DownloadUtils.getInstance().stop();
                    WarehouseStorageApplication.getInstance().removeAllActivity();
                    if (upgradeVersionListener != null) {
                        upgradeVersionListener.exit();
                    }
                }
            });

        });
        return baseDialog;
    }

    private static void download(Context context, String url, String fileName, String md5, ViewHolder viewHolder) {
        // 开始下载了，但是任务没有完成，代表正在下载，那么暂停下载。
        if (mDownloadRequest != null && mDownloadRequest.isStarted() && !mDownloadRequest.isFinished()) {
            // 暂停下载。
            mDownloadRequest.cancel();
        } else if (mDownloadRequest == null || mDownloadRequest.isFinished()) {// 没有开始或者下载完成了，就重新下载。
            mDownloadRequest = DownloadUtils.getApkDownloadRequest(context, url, fileName);
            // what 区分下载。
            // downloadRequest 下载请求对象。
            // downloadListener 下载监听。
            DownloadUtils.getInstance().download(context, DownloadUtils.DOWNLOAD_APK_REQUEST_CODE, mDownloadRequest, new DownloadListener() {

                @Override
                public void onStart(int what, boolean isResume, long beforeLength, Headers headers, long allCount) {
                    LogUtils.i("onStart:what【" + what + "】---isResume【" + isResume + "】---beforeLength【" + beforeLength + "】---allCount【" + allCount + "】");
                    if (DownloadUtils.DOWNLOAD_APK_REQUEST_CODE == what) {
                        viewHolder.prompt.setText("下载中");
                        viewHolder.numberProgressBar.setProgress(0);
                        viewHolder.upgradeErrorLayout.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onDownloadError(int what, Exception exception) {
                    LogUtils.i("onDownloadError:what【" + what + "】---exception【" + exception.toString() + "】---messageContent【" + DownloadUtils.getErroMessage(exception) + "】");
                    if (DownloadUtils.DOWNLOAD_APK_REQUEST_CODE == what) {
                        viewHolder.errorMessage.setText(DownloadUtils.getErroMessage(exception));
                        viewHolder.upgradeErrorLayout.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onProgress(int what, int progress, long fileCount, long speed) {
                    LogUtils.i("onProgress:what【" + what + "】---progress【" + progress + "】---fileCount【" + fileCount + "】---speed【" + speed + "】");
                    if (DownloadUtils.DOWNLOAD_APK_REQUEST_CODE == what) {
                        viewHolder.numberProgressBar.setProgress(progress);
                    }
                }

                @Override
                public void onFinish(int what, String filePath) {
                    LogUtils.i("onFinish:what【" + what + "】---filePath【" + filePath + "】");
                    if (DownloadUtils.DOWNLOAD_APK_REQUEST_CODE == what) {
                        String localMd5 = MD5Utils.encryptFile(new File(filePath));
                        if (md5.equals(localMd5)) {
                            LogUtils.i("安装应用");
                            //关闭连接
                            DownloadUtils.getInstance().stop();
                            WarehouseStorageApplication.getInstance().removeAllActivity();
                            PackageUtils.installNormal(context, filePath);
                        } else {
                            viewHolder.errorMessage.setText("MD5校验失败");
                            viewHolder.upgradeErrorLayout.setVisibility(View.VISIBLE);
                        }
                    }
                }

                @Override
                public void onCancel(int what) {
                    LogUtils.i("onCancel:what【" + what + "】");
                }

            });
        }

    }

}
